<?php


namespace App\Api\Controllers;


use App\Api\Controllers\UploadController as file;
use App\Models\Area;
use App\Models\Jd;
use App\Models\Order;
use App\Models\Pay\Notify;
use App\Models\Product;
use App\Models\ProductSku;
use App\Models\Rule;
use EclpOrderQueryOrderPacksRequest;
use Illuminate\Http\Request;
use JdClient;
use LdopReceiveTraceGetRequest;


class IndexController extends Controller
{
    //关于
    public function about()
    {
        $res = Rule::where('key','about_us')->first();
        $data = [];
        $data[] = $res?$res['content']:[];
        return $this->responseData($data);
    }

    //客户服务
    public function service()
    {
        $time = Rule::where('key','service_time')->first();
        $tel = Rule::where('key','service_telephone')->first();
        $data = [
            'service_time' => $time?$time['value']:'',
            'service_telephone' => $tel?$tel['value']:'',
        ];
        return $this->responseData($data);
    }

    public function uploads(Request $request)
    {
        if(!$request->imgs){
            return $this->responseFailed('参数错误');
        }
        $file = new file();
        $res = $file->uploadImage($request->file('imgs'));
        if(!$res['code']){
            return $this->responseFailed($res['msg']);
        }
        return $res;
    }

    public function area(Request $request)
    {
        $pid = $request->input('pid',0);
        $areaList = Area::where('pid',$pid)
            ->select('pid','id','name')
            ->get()
            ->toArray();

        return $this->responseData($areaList);
    }

    /*
     * 京东回调
     */
    public function jdback(Request $request){
        set_time_limit(0);
        ignore_user_abort(true);
        $EclpSoNo = $request->get('eclpSoNo');
        $order_id = $request->get('order_id');
        $path = storage_path().'/logs/';
        file_put_contents($path.'/jd-uporder-param-'.date('Y-m-d').'.log',$EclpSoNo.'---'.$order_id.PHP_EOL, FILE_APPEND);

        if(!$EclpSoNo || !$order_id){
            file_put_contents($path.'/jd-uporder-param-queshao-'.date('Y-m-d').'.log',$EclpSoNo.'---'.$order_id.PHP_EOL, FILE_APPEND);
            return false;
        }
        sleep(2);
        $jd_appkey = Rule::getValueByWhere('jd_appkey');
        $jd_appsecret = Rule::getValueByWhere('jd_appsecret');
        $jd_access_token = Rule::getValueByWhere('jd_access_token');

        $c = new JdClient();
        $c->appKey = $jd_appkey;
        $c->appSecret = $jd_appsecret;
        $c->accessToken = $jd_access_token;
        $c->serverUrl = "https://api.jd.com/routerjson";
        //获取运单号
        $req1 = new EclpOrderQueryOrderPacksRequest();
        $req1->setEclpSoNo( $EclpSoNo );
        $resp1 = $c->execute($req1, $jd_access_token);
        file_put_contents($path.'/jd-uporder-ok-'.date('Y-m-d').'.log',$order_id.'---'.json_encode($resp1).PHP_EOL, FILE_APPEND);
        //print_r($resp1);
        if($resp1->code == 0){
            $rest =  $resp1->queryorderpacks_result;
            //print_r($rest);
            $wayBill  = $rest[0];
            //print_r($wayBill);
            Order::updateSendStatus($order_id,$wayBill->wayBill);
        }else{
            file_put_contents($path.'/jd-uporder-error-'.date('Y-m-d').'.log',$order_id.'---'.json_encode($resp1).PHP_EOL, FILE_APPEND);
        }
    }


    /*
     *  物流
     */
    public function jdExpress(Request $request){
        try{
            $order = Order::find($request->order_id);
            if (empty($order)) {
                uexception('订单不存在');
            }
            if (empty($order['ship_no'])) {
                uexception('订单未发货');
            }
            $jd_appkey = Rule::getValueByWhere('jd_appkey');
            $jd_appsecret = Rule::getValueByWhere('jd_appsecret');
            $jd_access_token = Rule::getValueByWhere('jd_access_token');
            $c = new JdClient();
            $c->appKey = $jd_appkey;
            $c->appSecret = $jd_appsecret;
            $c->accessToken = $jd_access_token;
            $c->serverUrl = "https://api.jd.com/routerjson";
            $req = new LdopReceiveTraceGetRequest();
            $req->setCustomerCode( "027K306264" );//商家编码
            $req->setWaybillCode( $order->ship_no );
            //$req->setWaybillCode( 'JDVE00186267278' );
            $resp = $c->execute($req, $c->accessToken);
            if($resp->code==0){
                $result = $resp->querytrace_result;
                $data = [];
                $express = [];
                if($result->code==100){
                    //$rev_data = array_reverse($result->data);
                    $rev_data = $result->data;
                    foreach ($rev_data as $val) {
                        $express[] =  json_decode(json_encode($val),true);
                    }
                }
                $data['code'] = $result->code;
                $data['messsage'] = $result->messsage;
                $data['express'] = $express;
                return $this->responseSuccess($data);
            }
        }catch (\Exception $e){
            return $this->responseFailed($e->getMessage());
        }

    }

    public function test()
    {
        try{

        }catch (\Exception $e) {
            return $this->responseFailed($e->getMessage());
        }
        //$id = [19];
        //$id = [21];
        //31   20190804121552774730 后台这个订单暂时不补发
        //$id = [22,23,25];
        //$id = [28,29,30,32];
        // $id = [34,35];
        //$id = [62,63,65,66,67,68,70,72,73];
       /* $id = [79];
        foreach ($id as $val){
            $order = Order::find($val);
            if($order){
                Jd::pushJdOrder($order);
            }
        }*/
        /*
         * //京东订单推送
         *   $id = [19,21,22,23,25,28,29,30];
            foreach ($id as $val){
                $order = Order::find($val);
                if($order){
                    Jd::pushJdOrder($order);
                }
            }
         * */
        //ProductSpec::getSpecItem(1);
        //ProductSku::getSkuMinPrice(5);
        /*  $cart = [14,15];
          Order::postfee(8,$cart);*/

    }
}